var crypto = require('crypto');

exports.generatePassword = function(pass) {
		var salt = generateSalt();
		return salt + md5(pass + salt);
};

exports.validatePassword = function(plainPass, hashedPass) {
	var salt = hashedPass.substr(0, 10);
	var validHash = salt + md5(plainPass + salt);
	return hashedPass === validHash;
};

var generateSalt = function() {
	var set = '0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ';
	var salt = '';
	for ( var i = 0; i < 10; i++) {
		var p = Math.floor(Math.random() * set.length);
		salt += set[p];
	}
	return salt;
};

var md5 = function(str) {
	return crypto.createHash('md5').update(str).digest('hex');
};

exports.generateToken = function() {
	return generateSalt() + Date.now();
};

// 如果第二次参数不为null，则生成随机的纯数字串，否则生成随机的字符串。
exports.generateRandomAlphaNum = function(len, radix) {
    radix = radix ? 10 : 36;
    var rdmString = "";
    for (; rdmString.length < len; rdmString += Math.random().toString(radix).substr(2));
    return rdmString.substr(0, len);
}